﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using InventoryManagement;
using MII_FIF.Common;

namespace MII_FIF.Layouts.MII_FIF
{
    public partial class FormWorkOrder : LayoutsPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Generic.IsUserInGroup(Configuration.WorkOrderGroupName))
            {
                ((Label)Header.FindControl("lblHeader")).Text = "Vendor LogBook - Form Work Order";
                if (!IsPostBack)
                {
                    ViewState["EditMode"] = false;
                    if (Request.QueryString["ID"] != null)
                    {
                        ViewState["ID"] = Request.QueryString["ID"].ToString();
                        ViewState["EditMode"] = true;
                    }
                    Initialize();
                }
            }
            else
            {
                Response.Redirect(Generic.GenLink("/"));
            }
        }
        
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/VendorLogBook/ViewWorkOrder.aspx"));
        }

        void Initialize()
        {
            #region BindDDL
            Inventory_Physical physical = new Inventory_Physical();
            physical.IsDeleted = false;
            DataTable phyColl = physical.SelectByParam();
            Generic.BindDDL(ddlLabelName, phyColl, Inventory_Physical_Fields.LabelName.ToString(), Inventory_Physical_Fields.ID.ToString());
            Vendor vendor = new Vendor();
            vendor.IsDeleted = false;
            DataTable dtVendor = vendor.SelectByParam();
            Generic.BindDDL(ddlVendor, dtVendor, Vendor_Fields.Title.ToString(), Vendor_Fields.ID.ToString());
            #endregion
            //UpdateLabelName();
            //UpdateVendor();

            if (Request.QueryString["ID"] != null)
            {
                Guid ID = Guid.Empty;
                if (Guid.TryParse(Request.QueryString["ID"], out ID))
                {
                    Work_Order workOrder = new Work_Order();
                    workOrder.ID = ID;
                    workOrder.Select();
                    txtWorkOrderNo.Text = workOrder.NoWO;
                    txtTanggal.Text = workOrder.Date.HasValue ? workOrder.Date.Value.ToString("d MMM yyyy") : null;
                    ddlLabelName.SelectedValue = workOrder.ID_LabelName.ToString();
                    ddlLabelName_SelectedIndexChanged(this, EventArgs.Empty);
                    ddlVendor.SelectedValue = workOrder.ID_Vendor.ToString();
                    txtVendorName.Text = workOrder.Name;
                    lblPIC.Text = workOrder.PIC;
                    chkSystemConfiguration.Checked = workOrder.Svc_SysConfig.HasValue ? workOrder.Svc_SysConfig.Value : false;
                    chkTroubleshooting.Checked = workOrder.Svc_Troubleshooting.HasValue ? workOrder.Svc_Troubleshooting.Value : false;
                    chkHardware.Checked = workOrder.Svc_Hardware.HasValue ? workOrder.Svc_Hardware.Value : false;
                    chkDataBackup.Checked = workOrder.Svc_DataBackup.HasValue ? workOrder.Svc_DataBackup.Value : false;
                    chkSoftwareUpdate.Checked = workOrder.Svc_Software.HasValue ? workOrder.Svc_Software.Value : false;
                    chkUpgrade.Checked = workOrder.Svc_Upgrade.HasValue ? workOrder.Svc_Upgrade.Value : false;
                    chkSystemConfiguration.Checked = workOrder.Svc_SysConfig.HasValue ? workOrder.Svc_SysConfig.Value : false;
                    txtDescription.Text = workOrder.Description;
                    txtNote.Text = workOrder.Note;
                    txtStartDate.Text = workOrder.StartDate.HasValue ?  workOrder.StartDate.Value.ToString("d MMM yyyy") : null;
                    txtFinishDate.Text = workOrder.FinishDate.HasValue ? workOrder.FinishDate.Value.ToString("d MMM yyyy") : null;
                    ViewState["Link"] = workOrder.URLAttachment;

                    Pick_Up pickUp = new Pick_Up();
                    pickUp.ID_WorkOrder = ID;
                    DataTable dtPickUp = pickUp.SelectByParam();                

                    GridItem.DataSource = dtPickUp;
                    GridItem.DataBind();
                    ViewState["dtPickUp"] = dtPickUp;
                    ViewState["dtPickUpEdit"] = dtPickUp;

                    lblFileName.Text = Generic.GetFileNameFromUrl(workOrder.URLAttachment);
                    btnDownload.Visible = true;
                    lblFileName.Visible = true;
                    FUAttachment.Visible = false;
                }
            }
            else
            {
                lblPIC.Text = SPContext.Current.Web.CurrentUser.Name;
                DataTable dtPickUp = new DataTable();
                dtPickUp.Columns.Add(new DataColumn("Item", typeof(string)));
                dtPickUp.Columns.Add(new DataColumn("Quantity", typeof(string)));
                dtPickUp.Columns.Add(new DataColumn("SerialNumber", typeof(string)));
                dtPickUp.Columns.Add(new DataColumn("Accessories", typeof(string)));
                dtPickUp.Columns.Add(new DataColumn("ID", typeof(string)));

                GridItem.DataSource = dtPickUp;
                GridItem.DataBind();
                ViewState["dtPickUp"] = dtPickUp;

                btnDownload.Visible = false;
                lblFileName.Visible = false;
                FUAttachment.Visible = true;
            }
        }

        bool validasi()
        {
            bool check = true;
            lblerror.Text = string.Empty;
            if (!(bool)ViewState["EditMode"])
            {
                if (!FUAttachment.HasFile)
                {
                    lblerror.Text += "Please upload attachment. <br />"; check = false;
                }
                else if (Generic.checkUploadedFileName(FUAttachment.FileName))
                {
                    lblerror.Text += "Uploaded file name cannot contains # % & * : < > ? /  { | } <br />"; check = false;
                }
            }            
            return check;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (validasi())
            {
                Work_Order workOrder = new Work_Order();
                workOrder.ID_LabelName = StringUtil.ToGuid(ddlLabelName.SelectedValue);
                workOrder.NoWO = txtWorkOrderNo.Text;
                workOrder.Date = DateTime.ParseExact(txtTanggal.Text, "d MMM yyyy", System.Globalization.CultureInfo.CurrentCulture);
                workOrder.PIC = lblPIC.Text;
                workOrder.ID_Vendor = StringUtil.ToGuid(ddlVendor.SelectedValue);
                workOrder.Name = txtVendorName.Text;
                workOrder.Svc_SysConfig = chkSystemConfiguration.Checked;
                workOrder.Svc_Troubleshooting = chkTroubleshooting.Checked;
                workOrder.Svc_Hardware = chkHardware.Checked;
                workOrder.Svc_DataBackup = chkDataBackup.Checked;
                workOrder.Svc_Software = chkSoftwareUpdate.Checked;
                workOrder.Svc_Upgrade = chkUpgrade.Checked;
                workOrder.Description = txtDescription.Text;
                workOrder.Note = txtNote.Text;
                workOrder.StartDate = DateTime.ParseExact(txtStartDate.Text, "d MMM yyyy", System.Globalization.CultureInfo.CurrentCulture);
                workOrder.FinishDate = DateTime.ParseExact(txtFinishDate.Text, "d MMM yyyy", System.Globalization.CultureInfo.CurrentCulture);                

                if (Request.QueryString["ID"] != null)
                {
                    Guid ID = Guid.Empty;
                    if (Guid.TryParse(Request.QueryString["ID"], out ID))
                    {
                        workOrder.URLAttachment = ViewState["Link"] as string;
                        workOrder.ID = ID;
                        workOrder.Update();
                        using (DataTable dtPickUp = ViewState["dtPickUpEdit"] as DataTable)
                        {
                            foreach (DataRow row in dtPickUp.Rows)
                            {
                                Pick_Up pickUp = new Pick_Up();
                                pickUp.ID = StringUtil.ToGuid(row["ID"].ToString());
                                pickUp.Delete();
                            }
                        }

                        using (DataTable dtPickUp = ViewState["dtPickUp"] as DataTable)
                        {
                            foreach (DataRow row in dtPickUp.Rows)
                            {
                                Pick_Up pickUp = new Pick_Up();
                                pickUp.ID = StringUtil.ToGuid(row["ID"].ToString());
                                pickUp.ID_WorkOrder = ID;
                                pickUp.Item = row["Item"].ToString();
                                pickUp.Quantity = StringUtil.ToInt32(row["Quantity"].ToString());
                                pickUp.SerialNumber = row["SerialNumber"].ToString();
                                pickUp.Accessories = row["Accessories"].ToString();
                                pickUp.Insert();
                            }
                            ViewState["dtPickUpEdit"] = dtPickUp;
                        }
                    }
                }
                else
                {
                    Guid ID = Guid.NewGuid();
                    workOrder.URLAttachment = Generic.UploadFile(FUAttachment);
                    workOrder.ID = ID;
                    workOrder.Insert();
                    using (DataTable dtPickUp = (DataTable)ViewState["dtPickUp"])
                    {
                        foreach (DataRow row in dtPickUp.Rows)
                        {
                            Pick_Up pickUp = new Pick_Up();
                            pickUp.ID = StringUtil.ToGuid(row["ID"].ToString());
                            pickUp.ID_WorkOrder = ID;
                            pickUp.Item = row["Item"].ToString();
                            pickUp.Quantity = StringUtil.ToInt32(row["Quantity"].ToString());
                            pickUp.SerialNumber = row["SerialNumber"].ToString();
                            pickUp.Accessories = row["Accessories"].ToString();
                            pickUp.Insert();
                        }
                    }
                }
                Response.Redirect(Generic.GenLink("/_layouts/MII_FIF/VendorLogBook/ViewWorkOrder.aspx"));
            }
        }

        #region GridItem
        protected void GridItem_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DataTable dtPickUp = ViewState["dtPickUp"] as DataTable;
            dtPickUp.Rows[e.RowIndex]["Item"] = ((TextBox)GridItem.Rows[e.RowIndex].FindControl("txtItem")).Text;
            dtPickUp.Rows[e.RowIndex]["Quantity"] = ((TextBox)GridItem.Rows[e.RowIndex].FindControl("txtQuantity")).Text;
            dtPickUp.Rows[e.RowIndex]["SerialNumber"] = ((TextBox)GridItem.Rows[e.RowIndex].FindControl("txtSerialNumber")).Text;
            dtPickUp.Rows[e.RowIndex]["Accessories"] = ((TextBox)GridItem.Rows[e.RowIndex].FindControl("txtAccessories")).Text;
            GridItem.EditIndex = -1;
            GridItem.DataSource = dtPickUp;
            GridItem.DataBind();
            ViewState["dtPickUp"] = dtPickUp;
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        protected void GridItem_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridItem.EditIndex = -1;
            GridItem.DataSource = ViewState["dtPickUp"] as DataTable;
            GridItem.DataBind();
            btnAdd.Enabled = true;
            btnDelete.Enabled = true;
            btnCancel.Enabled = true;
            btnSubmit.Enabled = true;
        }

        protected void GridItem_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridItem.EditIndex = e.NewEditIndex;
            GridItem.DataSource = ViewState["dtPickUp"] as DataTable;
            GridItem.DataBind();

            btnAdd.Enabled = false;
            btnDelete.Enabled = false;
            btnCancel.Enabled = false;
            btnSubmit.Enabled = false;
        }

        protected void GridItem_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridItem.PageIndex = e.NewPageIndex;
            GridItem.DataSource = ViewState["dtPickUp"] as DataTable;
            GridItem.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            DataTable dtPickUp = (DataTable)ViewState["dtPickUp"];
            DataRow row = dtPickUp.NewRow();
            row["Item"] = txtItem.Text;
            row["Quantity"] = txtQuantity.Text;
            row["SerialNumber"] = txtSerialNumber.Text;
            row["Accessories"] = txtAccessories.Text;
            row["ID"] = Guid.NewGuid();
            dtPickUp.Rows.Add(row);

            GridItem.DataSource = dtPickUp;
            GridItem.DataBind();
            ViewState["dtPickUp"] = dtPickUp;
            txtItem.Focus();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool delete = false;
            DataTable dtPickUp = ViewState["dtPickUp"] as DataTable;
            foreach (GridViewRow row in GridItem.Rows)
            {
                CheckBox chk = (CheckBox)row.FindControl("chk");
                if (chk != null)
                    if (chk.Checked)
                    {
                        delete = true;
                    }
            }
            if (delete)
            {
                for (int i = GridItem.Rows.Count - 1; i > -1; i--)
                {
                    CheckBox chk = (CheckBox)GridItem.Rows[i].FindControl("chk");
                    if (chk != null)
                        if (chk.Checked)
                        {
                            dtPickUp.Rows.RemoveAt(i + GridItem.PageIndex * GridItem.PageSize);
                        }
                }
                GridItem.DataSource = dtPickUp;
                GridItem.DataBind();
                ViewState["dtPickUp"] = dtPickUp;
            }
        }
        #endregion

        protected void ddlLabelName_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateLabelName();            
        }

        void UpdateLabelName()
        {
            if (!ddlLabelName.SelectedValue.Equals("-1"))
            {
                Inventory_Physical physical = new Inventory_Physical();
                physical.ID = StringUtil.ToGuid(ddlLabelName.SelectedValue);
                physical.Select();
                System_Brand brand = new System_Brand();
                brand.ID = physical.ID_SysBrand;
                brand.Select();
                System_Type type = new System_Type();
                type.ID = physical.ID_SysType;
                type.Select();
                lblBrand.Text = brand.Title;
                lblCategory.Text = type.Title;
                lblSN.Text = physical.SerialNumber;
                ddlLabelName.Focus();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {

            string script =
                           "function download() {" +
                           "var link ='" + ViewState["Link"] + "';" +
                           "var retvalue = window.open('" + Generic.GenLink("/_layouts/MII_FIF/Download.aspx") + "?links=' + link"
                         + ", '', 'width=1000,height=1000');}";

            Page.ClientScript.RegisterClientScriptBlock(typeof(System.Web.UI.Page), "opendownload", script, true);
        }
    }
}
